from types import MethodType


# 面向对象高级编程


class StudentOrigin(object):
    pass


class StudentSlots(object):
    __slots__ = ('name', 'age')


def set_age(self, age):
    self.age = age


def set_score(self, score):
    self.score = score


def test_one():
    # 实例绑定熟属性
    s = StudentOrigin()
    s.name = 'Michael'
    print(s.name)
    # 实例绑定方法
    s.set_age = MethodType(set_age, s)
    s.set_age(25)
    print(s.age)
    # 对另一个实例不起作用
    try:
        s2 = StudentOrigin()
        s2.set_age(25)
    except AttributeError:
        print('不存在该方法')
    # 通过给class绑定方法实现给所有实例都绑定方法
    StudentOrigin.set_score = set_score
    try:
        s.set_score(5)
        print(s.score)
    except AttributeError:
        print('不存在该方法')

    # 使用 __slot__ 限制实例属性
    s_slot = StudentSlots()
    s_slot.name = 'Michael'
    s_slot.age = 15
    try:
        s_slot.score = 99
    except AttributeError:
        print('绑定属性错误')


if __name__ == '__main__':
    test_one()
